<template>
  <div class="account-add-wrapper">
    <TitleBar title="添加账号配置"></TitleBar>
    <div class="account-add-content">
      <Card class="account-add-card" :bordered="false">
        <Form
          :model="form"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
          class="account-form"
        >
          <Form.Item
            label="账户名"
            name="accountName"
            :rules="[{ required: true, message: '请输入账户名' }]"
          >
            <Input
              v-model:value="form.accountName"
              placeholder="请输入账户名（用作唯一标识）"
              :maxlength="50"
              size="large"
            />
          </Form.Item>

          <Form.Item
            label="期货公司名称"
            name="brokerName"
            :rules="[{ required: true, message: '请输入期货公司名称' }]"
          >
            <Input
              v-model:value="form.brokerName"
              placeholder="请输入期货公司名称"
              :maxlength="100"
              size="large"
            />
          </Form.Item>

          <!-- <Form.Item
            label="期货公司代码"
            name="brokerId"
            :rules="[{ required: true, message: '请输入期货公司代码' }]"
          >
            <Input
              v-model:value="form.brokerId"
              placeholder="请输入期货公司代码（如：9999）"
              :maxlength="20"
              size="large"
            />
          </Form.Item> -->

          <Form.Item
            label="交易服务器前置"
            name="tradeFront"
            :rules="[
              { required: true, message: '请输入交易服务器前置地址' },
              {
                pattern: /^tcp:\/\/[\d.]+:\d+$/,
                message: '地址格式不正确，应为: tcp://ip:port',
              },
            ]"
          >
            <Input
              v-model:value="form.tradeFront"
              placeholder="tcp://192.168.1.100:41205"
              :maxlength="100"
              size="large"
            />
          </Form.Item>

          <Form.Item
            label="行情服务前置"
            name="marketFront"
            :rules="[
              { required: true, message: '请输入行情服务前置地址' },
              {
                pattern: /^tcp:\/\/[\d.]+:\d+$/,
                message: '地址格式不正确，应为: tcp://ip:port',
              },
            ]"
          >
            <Input
              v-model:value="form.marketFront"
              placeholder="tcp://192.168.1.100:41213"
              :maxlength="100"
              size="large"
            />
          </Form.Item>
        </Form>
        <div class="button-group">
          <Button
            type="primary"
            size="large"
            :loading="saving"
            :disabled="saving"
            class="save-btn"
            @click="handleSave"
          >
            {{ saving ? "保存中..." : "保存配置" }}
          </Button>
          <Button size="large" @click="handleCancel" class="cancel-btn">
            取消
          </Button>
        </div>
      </Card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Card, Form, Input, Alert, Button, message } from "ant-design-vue";
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
import { emit, listen } from "@tauri-apps/api/event";
import { AccountConfigManager } from "../config/accountConfig";
import type { AccountConfig } from "../config/ctpConfig";
import TitleBar from "@/components/TitleBar.vue";

// 响应式数据
const saving = ref(false);
const validationErrors = ref<string[]>([]);

const form = reactive<Partial<AccountConfig>>({
  accountName: "",
  brokerName: "",
  brokerId: "9999",
  tradeFront: "",
  marketFront: "",
});

// 保存账号配置
const handleSave = async () => {
  try {
    // 验证表单
    const errors = AccountConfigManager.validateAccount(form);
    console.log(errors);
    if (errors.length > 0) {
      validationErrors.value = errors;
      return;
    }

    saving.value = true;
    validationErrors.value = [];

    // 构建完整的账号配置
    const accountConfig: AccountConfig = {
      accountName: form.accountName!,
      brokerName: form.brokerName!,
      brokerId: form.brokerId!,
      tradeFront: form.tradeFront!,
      marketFront: form.marketFront!,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
    };

    // 通知主窗口保存配置
    await emit("save-account-config", { account: accountConfig });

    message.success("账号配置添加成功");

    // 通知主窗口配置已更新
    await emit("account-config-updated", { account: accountConfig });

    // 关闭窗口
    const currentWindow = WebviewWindow.getCurrent();
    await currentWindow.close();
  } catch (error) {
    console.error("保存账号配置失败:", error);
    message.error(
      "保存失败：" + (error instanceof Error ? error.message : "未知错误")
    );
  } finally {
    saving.value = false;
  }
};

// 取消操作
const handleCancel = async () => {
  const currentWindow = WebviewWindow.getCurrent();
  await currentWindow.close();
};

// 组件挂载时的初始化
onMounted(async () => {
  // 监听来自主窗口的编辑请求
  await listen("edit-account-config", (event: any) => {
    const accountConfig = event.payload as AccountConfig;
    if (accountConfig) {
      Object.assign(form, accountConfig);
    }
  });

  console.log("账号添加窗口已初始化");
});
</script>

<style scoped lang="less">
.account-add-wrapper {
  height: 100%;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.account-add-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100% - 40px);
}

.account-add-card {
  width: 100%;
  max-width: 600px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  height: 100%;
  border-radius: 0;
  box-sizing: border-box;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 0px; /* 隐藏滚动条 */
    background: transparent; /* 透明背景 */
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: transparent;
  }
  :deep(.ant-card-body ) {
    padding: 12px;
  }
}

.page-title {
  text-align: center;
  margin-bottom: 32px;
  font-size: 28px;
  font-weight: 600;
  color: #1890ff;
  letter-spacing: 1px;
}

.account-form .ant-form-item {
  margin-bottom: 20px;
}

.account-form .ant-form-item-label > label {
  font-weight: 500;
  color: #333;
}

.account-form .ant-input {
  border-radius: 8px;
  border: 1.5px solid #d9d9d9;
  transition: all 0.3s ease;
}

.account-form .ant-input:focus,
.account-form .ant-input:hover {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.error-messages {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 32px;
  margin-bottom: 0;
}

.button-group {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 10px;
}

.save-btn {
  background: #1890ff;
  border-color: #1890ff;
  border-radius: 8px;
  font-weight: 500;
  min-width: 120px;
  height: 40px;
}

.save-btn:hover,
.save-btn:focus {
  background: #40a9ff;
  border-color: #40a9ff;
}

.cancel-btn {
  border-radius: 8px;
  min-width: 120px;
  height: 40px;
  font-weight: 500;
}

.cancel-btn:hover,
.cancel-btn:focus {
  border-color: #1890ff;
  color: #1890ff;
}
</style>
